﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using ANGFLib;

namespace ANGF
{
	public partial class FormListModules : Form
	{
		public FormListModules()
		{
			InitializeComponent();
		}

		private void buttonClose_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void FormListModules_Load(object sender, EventArgs e)
		{
			this.listBoxModules.Items.Clear();
			foreach (var n in Scenarios.SeekModulesFromRegistryOnly(this, true))
			{
				this.listBoxModules.Items.Add(n);
			}
		}

        private void removeSub(RegistryKey parentRegistry,
            string keyName, MyXmlDoc item)
        {
            Util.RemoveRegistry(parentRegistry, keyName, item.xmlFilePath, (m, n) =>
            {
                this.listBoxModules.Items.Remove(item);
                MessageBox.Show(this, "削除しました。", this.Text);
            });
        }

		private void buttonRemove_Click(object sender, EventArgs e)
		{
			if (this.listBoxModules.SelectedIndex < 0) return;
			MyXmlDoc item = (MyXmlDoc)this.listBoxModules.Items[this.listBoxModules.SelectedIndex];
			if (MessageBox.Show(this, "削除しますか? (設定のみでファイルは消えません) " + createItemString(this.listBoxModules.SelectedIndex), this.Text, MessageBoxButtons.YesNo) == DialogResult.Yes)
			{
                try
                {
                    removeSub(Microsoft.Win32.Registry.CurrentUser, ANGFLib.Constants.RegistoryRoot, item);
                }
                catch (UnauthorizedAccessException exc)
                {
                    MessageBox.Show(this, "削除する権限がありません。管理者で実行してください。" + exc.ToString(), this.Text);
                    return;
                }
                catch (System.Security.SecurityException exc)
                {
                    MessageBox.Show(this, "削除する権限がありません。管理者で実行してください。" + exc.ToString(), this.Text);
                    return;
                }
			}
		}

		private string createItemString(int index)
		{
			if (index < 0) return "";
			MyXmlDoc n = (MyXmlDoc)this.listBoxModules.Items[index];
			if (n == null) return "";
			return n.id + " " + n.name + (n.startupModule ? " (STATUP) " : " ") + n.DisplayFilePath;
		}

		private void listBoxModules_MeasureItem(object sender, MeasureItemEventArgs e)
		{
			string s = createItemString(e.Index);
			SizeF size = e.Graphics.MeasureString(s, this.listBoxModules.Font, this.listBoxModules.ClientSize.Width);
			e.ItemHeight = (int)size.Height;
		}

		private void listBoxModules_DrawItem(object sender, DrawItemEventArgs e)
		{
			e.DrawBackground();
			string s = createItemString(e.Index);
			e.Graphics.DrawString(s, e.Font, new SolidBrush(e.ForeColor), e.Bounds);
			e.DrawFocusRectangle();
		}
	}
}
